#!/bin/sh
#desc:Background music service
#package:odbgmusic
#type:local

CONFILE=/etc/opendomo/music.conf
. $CONFILE

MPG123="/usr/bin/mpg123 -R --fifo $TMPFILE >$INFFILE"
IFS=$'\x0A'$'\x0D'

# Interface parameters

if test -e $TMPCTLPARM; then
	. $TMPCTLPARM
fi

# Select default album or select album
			
if ! test -z "$2"; then
	ALBUM="$2"
fi
		
start () {
	
	if ! test -e $PID; then

		# Add music info in PID
			
		ARTIST=`cat $MUSICDB | grep "($ALBUM)" | cut -f2 -d"\"" | sort -u`
		COVER=`cat $MUSICDB | grep "($ALBUM)" | grep cover | cut -f4 -d"\""`
			
		echo "ARTIST=\"$ARTIST\""	 >$PID
		echo "ALBUM=\"$ALBUM\"" 	>>$PID
		echo "COVER=\"$COVER\"" 	>>$PID
		echo "VOLUME=$VOLUME"		>>$PID
		echo "RDM=$RDM"			>>$PID
		echo "LOOP=$LOOP"		>>$PID

		# If running as root, it is necessary to start as admin

		if test "$USER" = "root"; then
			su -c '/usr/bin/bgshell "$MPG123"' admin
			chown admin:admin $PID
			chown admin:admin $INFFILE
		else
			/usr/bin/bgshell "$MPG123"
		fi
		
		# Delete previous temporal files and create new files

		rm -f $TMPPLAYED $TMPCURRENT $TMPPENDING
		touch $TMPPLAYED $TMPCURRENT $TMPPENDING
		chown admin:admin $TMPPLAYED $TMPCURRENT $TMPPENDING
		chmod a+w $TMPPLAYED $TMPCURRENT $TMPENDING

		# Change PID permissions

		chmod ugo+rw $PID
	
		# Load all songs in pending temporal file
		
		SONGS=`cat "$MUSICDB" | grep "($ALBUM)" | grep -v "cover" |  cut -f4 -d"\""`

		for song in "$SONGS"; do
			echo "$song"    >> $TMPPENDING	
		done
	
		# if mpg123 is playing something just change the songs list

		if test "MPG123" == "`tail -n1 $INFFILE  | cut -f2 -d" "`"; then

	        # change to the first song of the new list
			/usr/local/opendomo/bgmusicNext.sh 
		else

		# Start the feed script to mpg123
			/usr/bin/bgshell "/usr/local/opendomo/bgmusicFeedPlayer.sh" 
		fi
	fi
}

stop () {

	# Stop service and delete temporal files

	killall -TERM mpg123 2>/dev/null
	rm -f $PID $TMPFILE $TMPPENDING $TMPCURRENT $TMPPLAYED $TMPLAST	$INFFILE 2>/dev/null
	
}

restart () {
        stop
        start
}

status () {
	  if ! test -e $PID; then
                        echo "bgmusic not running"
                        exit 1
                else
                        echo "bgmusic is running"
                        exit 0
          fi
}


case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  status)
	status
	;;
  *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
	;;
esac

exit $?

